<template>
  <page-container>
    <a-spin :spinning="spinning" tip="正在加载...">
      <public-page-search
        @page-search-change="pageSearchChange"
        @onQuery="hnadlequeryBarStat"
      ></public-page-search>
      <a-card style="height: 100%; margin-top: 20px" size="small">
        <template #title>
          <div class="cardTile">
            <div style="display: flex; align-items: center">
              <div>
                警情趋势
                <span class="title" v-if="title && !isArrays(title)" ref="titleRefs">
                  "{{ title }}"
                </span>
                <span v-else ref="titleRefs">
                  <span v-for="(item, index) in title" :key="index">
                    <span v-if="item">"{{ item }}"</span>
                    <span v-if="item != '' && isSpace">
                      {{ index == title.length - 1 ? ' ' : '或' }}
                    </span>
                    <span v-if="item != '' && isSpace == false">
                      {{ index == title.length - 1 ? ' ' : '+' }}
                    </span>
                  </span>
                </span>
              </div>
              <div class="echartinfo" v-if="echartInfoData[0]?.name">
                <span>{{ echartInfoData[0].name }}</span>
                <span>
                  当前警情共
                  <span style="text-decoration: underline">{{ echartInfoData[0].data }}</span>
                  起
                  <span v-if="echartInfoData[0]?.seriesName == '去年同期'">
                    去年警情
                    <span style="text-decoration: underline">
                      {{ echartInfoData[0].data }}
                    </span>
                    起
                  </span>
                  &nbsp;
                  <span v-if="echartInfoData[1]?.seriesName == '去年同期'">
                    去年警情
                    <span style="text-decoration: underline">
                      {{ echartInfoData[1].data }}
                    </span>
                    起
                  </span>

                  <span style="margin-left: 31px">
                    <span v-show="ecahrtinfo.percent">同比：{{ ecahrtinfo.percent }}</span>
                    <span v-show="ecahrtinfo.hPercent" style="margin-left: 10px">
                      环比：{{ ecahrtinfo.hPercent }}
                    </span>
                  </span>
                </span>
                <span style="margin-left: 31px" v-if="ecahrtinfo.top3List?.length">
                  <span
                    v-for="(item, index) in ecahrtinfo.top3List"
                    :key="index"
                    style="margin-right: 10px"
                  >
                    <span v-show="item.caseNum">
                      {{ item.xqdwName }}：{{ item.caseNum }}
                      <span v-if="echartInfoData[0].data !== 0 ? true : false">
                        ({{ divide(item.caseNum, echartInfoData[0].data) }})
                      </span>
                    </span>
                  </span>
                </span>
              </div>
              <div v-else>
                <div>
                  <div class="echartinfo">
                    <span>
                      <span>
                        当前警情
                        <span style="text-decoration: underline">
                          {{ headerInfo.count }}
                        </span>
                        起
                      </span>
                      <span v-if="headerInfo.yoyCount" style="margin-left: 15px">
                        去年同期
                        <span style="text-decoration: underline">
                          {{ headerInfo.yoyCount }}
                        </span>
                        起
                      </span>
                      &nbsp;
                      <span style="margin: 0 0 0 31px" v-if="headerInfo.yoyPercent">
                        同比：{{ headerInfo.yoyPercent }}%
                      </span>
                      <span v-if="headerInfo.chainPercent">
                        环比：{{ headerInfo.chainPercent }}%
                      </span>
                    </span>
                  </div>
                  <span
                    class="echartinfo"
                    style="margin-left: 31px"
                    v-if="headerInfo.xqdwTop3?.length"
                  >
                    <span
                      v-for="(item, index) in headerInfo.xqdwTop3"
                      :key="index"
                      style="margin-right: 8px"
                    >
                      <span>
                        {{ item.xqdwName }}：{{ item.count }}
                        <span v-if="item.percent">({{ item.percent }}%)</span>
                      </span>
                    </span>
                  </span>
                </div>
              </div>
            </div>
          </div>
        </template>
        <timeline-chart
          :data="yoyList.dataList"
          :height="280"
          type="传统"
          :fieldNames="{ name: 'dataDate', values: ['caseNum', 'yoyCaseNum'] }"
          :legend="['当前警情', '去年同期']"
          @zrender:click="timeChartClickHandle"
          v-if="yoyList.dataList && yoyList.dataList.length"
          @handleMove="handelEachartMove"
          @Leave="handleLeave"
        />
        <a-empty v-else style="margin-top: 107px" />
      </a-card>
      <a-row :span="24">
        <a-col :span="12">
          <a-card class="classification" :span="20" style="height: 100%" size="small">
            <template v-slot:title>
              <div>
                接警类别
                <span class="title" v-if="title && !isArrays(title)">"{{ title }}"</span>
                <span v-else>
                  <span v-for="(item, index) in title" :key="index">
                    "{{ item }}"
                    <span>{{ index == title.length - 1 ? '' : '+' }}</span>
                  </span>
                </span>
              </div>
            </template>
            <pie
              :data="callList"
              :height="300"
              :fieldNames="{
                name: 'callSummaryName',
                value: 'caseNum',
              }"
              v-if="callList.length"
              @zrender:click="pieRenderClickHandleJq"
            />
            <a-empty v-else style="margin-top: 60px" />
          </a-card>
        </a-col>
        <a-col :span="12">
          <a-card class="classification" :span="20" style="height: 100%" size="small">
            <template v-slot:title>
              <div>
                反馈类别
                <span class="title" v-if="title && !isArrays(title)">"{{ title }}"</span>
                <span v-else>
                  <span v-for="(item, index) in title" :key="index">
                    "{{ item }}"
                    <span>{{ index == title.length - 1 ? '' : '+' }}</span>
                  </span>
                </span>
              </div>
            </template>
            <pie
              :data="dealList"
              :height="300"
              :fieldNames="{
                name: 'dealSummaryName',
                value: 'caseNum',
              }"
              v-if="dealList.length"
              @zrender:click="pieRenderClickHandle"
            />
            <a-empty v-else style="margin-top: 60px" />
          </a-card>
        </a-col>
      </a-row>
      <a-card class="classification" :span="20" style="height: 100%" size="small">
        <template v-slot:title>
          <div>
            辖区单位统计
            <span class="title" v-if="title && !isArrays(title)">"{{ title }}"</span>
            <span v-else>
              <span v-for="(item, index) in title" :key="index">
                "{{ item }}"
                <span>{{ index == title.length - 1 ? '' : '+' }}</span>
              </span>
            </span>
          </div>
        </template>
        <bar
          :data="xqdwList"
          :height="300"
          type="传统"
          :fieldNames="{
            name: 'xqdwName',
            value: 'caseNum',
          }"
          @zrender:click="chartClickHandleTimexq"
          v-if="xqdwList.length"
        />
        <a-empty v-else style="margin-top: 60px" />
      </a-card>
      <!-- 警情列表 -->
      <police-list-drawer
        v-model:visible="tabVisible"
        :title="titleData"
        :tabs="policeTabs"
        topicType="ct"
        :headerTile="echartInfo"
      ></police-list-drawer>
    </a-spin>
  </page-container>
</template>
<script lang="ts">
import { defineComponent, reactive, ref, onUnmounted, toRaw } from 'vue';
import bar from '@/components/charts/bar/index.vue';
import PublicPageSearch from '@/views/routine-analysis/list/components/researchList/index.vue';
import TimelineChart from '@/views/routine-analysis/statistics/components/line.vue';
import { queryBarStat } from '@/api/intelligentanalysis/echarts';
import Pie from '@/components/charts/pie/simple-pie/index.vue';
import PoliceListDrawer from '../components/police-list-drawer/index.vue';
import moment from 'moment';
import { PublicQueryState } from '@/views/intelligent-analysis/typing';
import { getInitParams } from '@/views/intelligent-analysis/js/publicQuery';
import { isNil, omit, isArray } from 'lodash';
import { querySummaryInfo } from '@/api/intelligentanalysis/grain';
export default defineComponent({
  name: '',
  components: { TimelineChart, bar, Pie, PoliceListDrawer, PublicPageSearch },
  setup() {
    const queryForm: PublicQueryState = reactive({
      ...getInitParams('statistics'),
      searchType: '1',
    });
    const policeTabs = ref<Array<any>>([]);
    const dateFormat = 'YYYY-MM-DD HH:mm:ss';
    const tabVisible = ref<boolean>(false);
    const titleData = ref<string>('');
    //图表接口
    const yoyList = ref<any>([]);
    const callList = ref<any>([]);
    const dealList = ref<any>([]);
    const xqdwList = ref<any>([]);
    const spinning = ref<boolean>(true);
    const title = ref<any>([]);
    const isSpace = ref<boolean>(false);
    const hnadlequeryBarStat = () => {
      spinning.value = true;
      if (queryForm.inputParams) {
        queryForm.inputParams = queryForm.inputParams.replace(/^\s+|\s+$/g, '');
        if (queryForm.inputParams.indexOf('|') > -1) {
          title.value = queryForm.inputParams.split('|');
          isSpace.value = true;
        } else if (queryForm.inputParams.indexOf(' ') > -1) {
          title.value = queryForm.inputParams.split(' ');
          isSpace.value = false;
        } else {
          title.value = queryForm.inputParams;
        }
      } else {
        title.value = '';
      }
      queryBarStat(toRaw(queryForm))
        .then(res => {
          yoyList.value = res.data.yoyList;
          xqdwList.value = res.data.xqdwList;
          callList.value = res.data.pieCall;
          dealList.value = res.data.pieDeal;
        })
        .finally(() => {
          spinning.value = false;
        });
      handlequerySummaryInfo();
    };
    const isArrays = value => {
      return isArray(value);
    };
    // 点击接警类别饼图
    const pieRenderClickHandleJq = e => {
      const dataIndex = e?.target?.dataIndex;
      if (!isNil(dataIndex)) {
        titleData.value = callList.value[dataIndex].classifyName;
        const callSummaryCode = callList.value[dataIndex].callSummaryCode;
        const paramsList = [
          {
            url: '/aitype/caseInfo/queryCaseInfo',
            params: reactive({
              ...omit(queryForm, ['classifyNames', 'callSummaryCodes', 'themeCode']),
              callSummaryCode,
              page: 1,
              size: 50,
            }),
          },
        ];
        //查询条件信息
        echartInfo.value = {
          time: queryForm.callTimeStart + ' 至 ' + queryForm.callTimeEnd,
          type: titleRefs.value.innerText,
        };
        policeTabs.value = paramsList;
        tabVisible.value = true;
      }
    };

    //点击反馈类别饼图
    const pieRenderClickHandle = e => {
      const dataIndex = e?.target?.dataIndex;
      if (!isNil(dataIndex)) {
        titleData.value = dealList.value[dataIndex].dealSummaryName;
        const dealSummaryCode = dealList.value[dataIndex].dealSummaryCode;
        const paramsList = [
          {
            url: '/aitype/caseInfo/queryCaseInfo',
            params: reactive({
              ...omit(queryForm, ['classifyNames', 'dealSummaryCodes', 'themeCode']),
              dealSummaryCode,
              page: 1,
              size: 50,
            }),
          },
        ];
        //查询条件信息
        echartInfo.value = {
          time: queryForm.callTimeStart + ' 至 ' + queryForm.callTimeEnd,
          type: titleRefs.value.innerText,
        };
        policeTabs.value = paramsList;
        tabVisible.value = true;
      }
    };

    //辖区单位统计
    const chartClickHandleTimexq = e => {
      titleData.value = xqdwList.value[e].xqdwName;
      const xqdwCode = xqdwList.value[e].xqdwCode;
      const paramsList = [
        {
          url: '/aitype/caseInfo/queryCaseInfo',
          params: reactive({
            ...queryForm,
            xqdwCode,
            page: 1,
            size: 50,
          }),
        },
      ];
      //查询条件信息
      echartInfo.value = {
        time: queryForm.callTimeStart + ' 至 ' + queryForm.callTimeEnd,
        type: titleRefs.value.innerText,
      };
      policeTabs.value = paramsList;
      tabVisible.value = true;
    };
    const titleRefs = ref();
    const echartInfo = ref<any>({});
    //折线图点击事件
    const timeChartClickHandle = (index, item) => {
      titleData.value = '警情趋势';
      const dataStart = `${item.dataDate} 00:00:00`;
      const dataEnd = `${item.dataDate} 23:59:59`;
      const lastYearStart = moment(dataStart).subtract(1, 'year').format(dateFormat);
      const lastYearEnd = moment(dataEnd).subtract(1, 'year').format(dateFormat);
      const paramsList = [
        {
          name: '当期警情',
          url: '/aitype/caseInfo/queryCaseInfo',
          params: reactive({
            ...queryForm,
            callTimeStart: dataStart,
            callTimeEnd: dataEnd,
            page: 1,
            size: 50,
          }),
        },
        {
          name: '去年同期',
          url: '/aitype/caseInfo/queryCaseInfo',
          params: reactive({
            ...queryForm,
            callTimeStart: lastYearStart,
            callTimeEnd: lastYearEnd,
            page: 1,
            size: 50,
          }),
        },
      ];
      //查询条件信息
      echartInfo.value = {
        time: item.dataDate,
        type: titleRefs.value.innerText,
      };
      policeTabs.value = paramsList;
      tabVisible.value = true;
    };
    let echartInfoData = ref<any>([]);
    let ecahrtinfo = ref<any>({});
    const handelEachartMove = value => {
      echartInfoData.value = value;
      let index = value[0].dataIndex;
      ecahrtinfo.value = yoyList.value.dataList[index];
    };
    const divide = (num1, num2) => {
      let t1, t2, r1, r2;
      try {
        t1 = num1.toString().split('.')[1].length;
      } catch (e) {
        t1 = 0;
      }
      try {
        t2 = num2.toString().split('.')[1].length;
      } catch (e) {
        t2 = 0;
      }
      r1 = Number(num1.toString().replace('.', ''));
      r2 = Number(num2.toString().replace('.', ''));
      let number = (r1 / r2) * Math.pow(10, t2 - t1) * 100;
      return number.toFixed(2) + '%';
    };
    const handleLeave = value => {
      if (value) {
        echartInfoData.value = [];
      }
    };
    let flag = ref<boolean>(true);
    const pageSearchChange = params => {
      Object.keys(queryForm).forEach(key => {
        Object.prototype.hasOwnProperty.call(params, key) && (queryForm[key] = params[key]);
      });
      if (flag.value) {
        hnadlequeryBarStat();
        flag.value = false;
      }
    };
    const headerInfo = ref<any>([]);
    const handlequerySummaryInfo = () => {
      querySummaryInfo(toRaw(queryForm)).then(res => {
        headerInfo.value = res.data;
      });
    };
    onUnmounted(() => {});
    return {
      headerInfo,
      isSpace,
      titleRefs,
      isArrays,
      divide,
      callList,
      spinning,
      dealList,
      xqdwList,
      yoyList,
      queryForm,
      policeTabs,
      tabVisible,
      titleData,
      timeChartClickHandle,
      chartClickHandleTimexq,
      pieRenderClickHandle,
      pieRenderClickHandleJq,
      pageSearchChange,
      hnadlequeryBarStat,
      title,
      handelEachartMove,
      ecahrtinfo,
      echartInfoData,
      handleLeave,
      echartInfo,
    };
  },
});
</script>
<style lang="less" scoped>
.cardTile {
  padding-top: 4px;
  font-size: 14px;
}
.title {
  margin-left: 20px;
  color: #afb9d2;
  font-size: 14px;
}

.echartinfo {
  display: inline-block;
  //   width: 500px;
  margin-left: 30px;

  color: #ffffff;
  color: #afb9d2;
  font-weight: 500;
  font-size: 14px;
  font-family: Source Han Sans CN;
  text-align: left;
}
:deep(.ant-card-head) {
  height: 48px;
  padding-top: 5px;
  font-size: 14px;
  background: #34363c;
}
</style>
